<template>
  <div v-if="visible" class="image-preview" @click="handleMaskClick">
    <!-- 遮罩层 -->
    <div class="preview-mask" :style="{ backgroundColor: maskBg }"></div>

    <!-- 图片容器：处理缩放、拖动 -->
    <div class="preview-canvas" ref="canvas" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
      @touchend="handleTouchEnd" @mousewheel="handleMouseWheel">
      <img v-if="currentImg" :src="currentImg" :style="imageStyle" alt="preview">
    </div>

    <!-- 缩略图栏（可选） -->
    <div v-if="images.length > 1" class="thumbnail-bar">
      <div v-for="(img, idx) in images" :key="idx" class="thumbnail-item" :class="{ active: idx === currentIndex }"
        @click="switchImage(idx)">
        <img :src="img.img" alt="thumbnail">
      </div>
    </div>

    <!-- 关闭按钮 -->
    <div class="preview-close" @click="close">×</div>
  </div>
</template>

<script>
export default {
  name: 'ImagePreview',
  props: {
    images: { type: Array, default: () => [] }, // 图片地址列表
    visible: { type: Boolean, default: true }, // 是否显示预览
    maskBg: { type: String, default: 'rgba(0,0,0,0.9)' }, // 遮罩背景
    initialIndex: { type: Number, default: 0 }, // 初始显示的图片索引
  },
  data() {
    return {
      currentIndex: this.initialIndex, // 当前显示的图片索引
      scale: 1, // 缩放比例
      translateX: 0, // 水平偏移
      translateY: 0, // 垂直偏移
      startTouch: null, // 触摸起始点
      isDragging: false, // 是否正在拖动
    };
  },
  computed: {
    currentImg() {
      return this.images[this.currentIndex];
    },
    imageStyle() {
      return {
        transform: `translate3d(${this.translateX}px, ${this.translateY}px, 0) scale(${this.scale})`,
        transformOrigin: 'center center',
        transition: this.isDragging ? 'none' : 'transform 0.2s',
      };
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.resetTransform(); // 显示时重置缩放和偏移
      }
    },
    currentIndex(val) {
      this.resetTransform(); // 切换图片时重置缩放和偏移
    },
  },
  methods: {
    // 重置缩放和偏移
    resetTransform() {
      this.scale = 1;
      this.translateX = 0;
      this.translateY = 0;
    },
    // 关闭预览
    close() {
      this.$emit('update:visible', false);
    },
    // 点击遮罩关闭（可配置是否允许）
    handleMaskClick(e) {
      if (e.target.classList.contains('image-preview')) {
        this.close();
      }
    },
    // 切换图片
    switchImage(index) {
      this.currentIndex = index;
    },
    // 触摸开始：记录初始位置
    handleTouchStart(e) {
      e.preventDefault();
      this.startTouch = {
        x: e.touches[0].clientX,
        y: e.touches[0].clientY,
        scale: this.scale,
        translateX: this.translateX,
        translateY: this.translateY,
      };
      this.isDragging = true;
    },
    // 触摸移动：处理拖动或缩放
    handleTouchMove(e) {
      e.preventDefault();
      if (!this.startTouch || !this.isDragging) return;

      const touch = e.touches[0];
      const dx = touch.clientX - this.startTouch.x;
      const dy = touch.clientY - this.startTouch.y;

      // 单指拖动
      if (e.touches.length === 1) {
        this.translateX = this.startTouch.translateX + dx;
        this.translateY = this.startTouch.translateY + dy;
      }
      // 双指缩放
      else if (e.touches.length === 2) {
        const distance = Math.hypot(
          e.touches[1].clientX - e.touches[0].clientX,
          e.touches[1].clientY - e.touches[0].clientY
        );
        const scaleFactor = distance / this.startTouch.distance; // 需提前记录初始双指距离
        this.scale = Math.max(0.5, Math.min(3, this.startTouch.scale * scaleFactor));
      }
    },
    // 触摸结束：重置状态
    handleTouchEnd() {
      this.isDragging = false;
      this.startTouch = null;
    },
    // 鼠标滚轮缩放
    handleMouseWheel(e) {
      e.preventDefault();
      const delta = e.wheelDelta > 0 ? 0.1 : -0.1;
      this.scale = Math.max(0.5, Math.min(3, this.scale + delta));
    },
  }
};
</script>

<style scoped>
.image-preview {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.preview-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.preview-canvas {
  position: relative;
  width: 100%;
  height: 80vh;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.preview-canvas img {
  max-width: 90%;
  max-height: 90%;
  object-fit: contain;
}

.thumbnail-bar {
  display: flex;
  justify-content: center;
  padding: 16px;
  gap: 8px;
}

.thumbnail-item {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  opacity: 0.7;
}

.thumbnail-item.active {
  opacity: 1;
  border: 2px solid #fff;
}

.preview-close {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 32px;
  color: #fff;
  cursor: pointer;
}
</style>